package com.yundingai.config;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.yundingai.ai.cache.RedisChatMemory;
import com.yundingai.ai.tools.PlanFunction;
import com.yundingai.ai.tools.StudentInfoFunction;
import com.yundingai.constants.AiConstant;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

@Configuration
public class SpringAIConfig {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ObjectMapper objectMapper;

    /**
     * 创建并返回一个ChatClient的Spring Bean实例。
     *
     * @param builder 用于构建ChatClient实例的构建者对象
     * @return 构建好的ChatClient实例
     */
    @Bean
    public ChatClient chatClient(ChatClient.Builder builder,
                                 PlanFunction planFunction,
                                 StudentInfoFunction studentInfoFunction
    ) {
        return builder
                .defaultSystem(AiConstant.SYSTEM_ROLE) // 设置默认的系统角色
                .defaultAdvisors(new SimpleLoggerAdvisor(), new MessageChatMemoryAdvisor(chatMemory())) // 设置默认的Advisor
                .defaultTools(planFunction,studentInfoFunction) // 设置默认的工具
                .build();
    }


    @Bean
    public ChatMemory chatMemory(){
        return new RedisChatMemory(redisTemplate,objectMapper);
    }

    /**
     * 创建并返回一个SimpleLoggerAdvisor的Spring Bean实例。
     */
    @Bean
    public Advisor simpleLoggerAdvisor() {
        return new SimpleLoggerAdvisor();
    }

    /**
     * 创建并返回一个VectorStore的Spring Bean实例。
     *
     * @param embeddingModel 向量模型
     */
    @Bean
    public VectorStore vectorStore(EmbeddingModel embeddingModel) {
        return SimpleVectorStore.builder(embeddingModel).build();
    }

}
